import 'package:fluent_ui/fluent_ui.dart';
import 'package:super_timetable_front/api/semester_api.dart';

import '../../api/test_level_api.dart';
import '../../components/data_table.dart';
import '../../global_setting.dart';
import '../../model/semester_model.dart';
import '../../model/test_level_model.dart';
import '../../utils/loading_utils.dart';
import '../app/app_dict_data.dart';

abstract class TestLevelField {}

///考试等级:查询字段
enum TestLevelQueryField implements TestLevelField {
  semester('学年学期'),
  name('名称'),
  status("状态");

  final String label;

  const TestLevelQueryField(this.label);
}

/// 考试等级:输入字段
enum TestLevelInputField implements TestLevelField {
  semester('学年学期', checked: true),
  name('名称', checked: true),
  remark('备注'),
  status("状态", isAdd: false);

  final String label;
  final bool checked, isAdd;

  const TestLevelInputField(
    this.label, {
    this.checked = false,
    this.isAdd = true,
  });

  String? validHandler(final String? val) {
    if (checked && (val == null || val.isEmpty)) {
      return '$label不能为空';
    }
    return null;
  }
}

///考试等级:视图模型
class TestLevelViewModel extends ChangeNotifier {
  //查询字段
  final _queryFields = <TestLevelQueryField, TextEditingController>{
    for (var field in TestLevelQueryField.values) field: TextEditingController()
  };

  //输入字段
  final _inputFields = <TestLevelInputField, TextEditingController>{
    for (var field in TestLevelInputField.values) field: TextEditingController()
  };

  ///获取控制器
  TextEditingController? getController<T extends TestLevelField>(
      final T field) {
    //查询字段
    if (field is TestLevelQueryField) {
      return _queryFields[field];
    }
    //输入字段
    if (field is TestLevelInputField) {
      return _inputFields[field];
    }
    return null;
  }

  ///获取字段值
  String? getFieldValue<T extends TestLevelField>(final T field) {
    final ctr = getController(field);
    if (ctr != null) {
      return ctr.text;
    }
    return null;
  }

  ///设置字段值
  void setFieldValue<T extends TestLevelField>(T field, String? val) {
    final controller = getController(field);
    if (controller != null) {
      controller.text = val ?? '';
    }
  }

  final _statusOpts = <ComboBoxItem<String>>[];

  ///获取状态选项集合
  List<ComboBoxItem<String>> get statusOpts => _statusOpts;

  ///加载字典
  void _loadDict(final List<Future<dynamic>> futures) {
    //状态
    if (_statusOpts.isEmpty) {
      final future = appDictData.buildOpts('status').then(
        (opts) {
          if (opts.isNotEmpty) {
            _statusOpts.addAll(opts);
          }
        },
      );
      futures.add(future);
    }
  }

  final _semesterMap = <String, String>{};
  final _semesterOpts = <ComboBoxItem<String>>[];

  ///获取学期标题
  String getSemesterTitle(final String id) => _semesterMap[id] ?? '';

  ///获取学期选项集合
  List<ComboBoxItem<String>> get semesterOpts => _semesterOpts;

  ///加载学期
  void _loadSemester(final List<Future<dynamic>> futures) {
    //学年学期
    if (_semesterMap.isEmpty) {
      final future = semesterApi
          .query(SemesterQueryReq(status: 1, index: 1, size: 100))
          .then((res) {
        final rows;
        if ((rows = res.rows).isNotEmpty) {
          for (var row in rows) {
            _semesterMap[row.id] = row.title;
            _semesterOpts.add(ComboBoxItem<String>(
              value: row.id,
              child: Text(row.title),
            ));
          }
        }
      });
      futures.add(future);
    }
  }

  ///加载初始化
  void loadInit({final VoidCallback? afterHandler}) async {
    final futures = <Future<dynamic>>[];
    //加载字典
    _loadDict(futures);
    //加载学年学期
    _loadSemester(futures);
    //请求同步
    if (futures.isNotEmpty) {
      await Future.wait(futures);
      //触发通知
      notifyListeners();
    }
    //处理回调
    if (afterHandler != null) {
      afterHandler.call();
    }
  }

  //清空查询字段
  void cleanQueryFields() {
    for (var controller in _queryFields.values) {
      controller.clear();
    }
  }

  ///清空输入字端
  void cleanInputFields() {
    for (var controller in _inputFields.values) {
      controller.clear();
    }
  }

  ///分页查询模型
  final queryModel = PageModel<TestLevelItemRes>();

  ///分页查询
  void query() async {
    try {
      loading.showLoading();
      //查询条件
      final status = getFieldValue(TestLevelQueryField.status);
      final req = TestLevelQueryReq(
        tenantId: globalSetting.tenant,
        semesterId: getFieldValue(TestLevelQueryField.semester) ?? '',
        name: getFieldValue(TestLevelQueryField.name) ?? '',
        status: int.tryParse(status ?? '') ?? -1,
      );
      //查询处理
      final res = await testLevelApi.query(req);
      if (res.isSuccessed) {
        queryModel.buildResData(res);
      }
      debugPrint('testLevelApi.query(req:${req.toMap()})=>$res');
    } finally {
      loading.dismiss();
    }
  }

  ///加载数据
  void getInfoById(final String id) async {
    try {
      loading.showLoading();
      //加载数据
      final res = await testLevelApi.info(id);
      if (res.isSuccessed) {
        setFieldValue(TestLevelInputField.semester, res.semesterId);
        setFieldValue(TestLevelInputField.name, res.name);
        setFieldValue(TestLevelInputField.status, '${res.status}');
        setFieldValue(TestLevelInputField.remark, res.remark);
        //触发通知
        notifyListeners();
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }

  ///新增处理
  void onAddHandler(final VoidCallback handler) async {
    try {
      loading.showLoading();
      //新增
      final req = TestLevelAddReq(
        tenantId: globalSetting.tenant,
        name: getFieldValue(TestLevelInputField.name) ?? '',
        remark: getFieldValue(TestLevelInputField.remark) ?? '',
        semesterId: getFieldValue(TestLevelInputField.semester) ?? '',
      );
      //提交
      final res = await testLevelApi.add(req);
      if (res.isSuccessed) {
        cleanInputFields();
        handler.call();
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }

  ///修改处理
  void onModifyHandler(final String id, final VoidCallback handler) async {
    try {
      loading.showLoading();
      //修改
      final status = getFieldValue(TestLevelInputField.status);
      final req = TestLevelModifyReq(
        id: id,
        name: getFieldValue(TestLevelInputField.name) ?? '',
        remark: getFieldValue(TestLevelInputField.remark) ?? '',
        semesterId: getFieldValue(TestLevelInputField.semester) ?? '',
        status: int.tryParse(status ?? '') ?? 1,
      );
      //提交
      final res = await testLevelApi.modify(req);
      if (res.isSuccessed) {
        cleanInputFields();
        handler.call();
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }

  ///删除处理
  void onDeleteHandler(final String id) async {
    try {
      loading.showLoading();
      //删除处理
      final res = await testLevelApi.delete(id);
      if (res.isSuccessed) {
        //重新加载数据
        query();
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }
}
